package com.itheima.cs.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import androidx.appcompat.app.AppCompatActivity;

import com.google.zxing.common.StringUtils;
import com.itheima.cs.dao.UserDao;
import com.itheima.cs.entity.Userinfo;

import okhttp3.*;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import static android.content.ContentValues.TAG;
import static android.content.Context.MODE_PRIVATE;

public class LoginManager{
    private static final String PREFS_NAME = "session_cookie";
    private static final String LOGIN_URL = "http://192.168.16.201:8090/k3cloud/Kingdee.BOS.WebApi.ServicesStub.AuthService.LoginByAppSecret.common.kdsvc";

    private static LoginManager instance;
    private final UserDao userDao;
    private final OkHttpClient client;
    private final Context context;


    private LoginManager(Context context) {
        this.context = context.getApplicationContext();
        userDao = new UserDao();
        client = new OkHttpClient();
    }

    public static synchronized LoginManager getInstance(Context context) {
        if (instance == null) {
            instance = new LoginManager(context.getApplicationContext());
        }
        return instance;
    }

    public void login(String username, String password, String createUserName, LoginCallback callback) {
        new Thread(() -> {
            Userinfo userinfo = userDao.getUserByUsernameAndPassword(username, password);
            if (userinfo == null) {
                callback.onFailure("扫码调拨系统登录失败，请检查用户名和密码");

                return;
            }

            int userId = userinfo.getId();
            SharedPreferences userPrefs = context.getSharedPreferences("user_info", MODE_PRIVATE);
            userPrefs.edit().putString("user_id", String.valueOf(userId)).apply();
            userPrefs.edit().putString("user_emp_number", userinfo.getEmpNumber()).apply();


            RequestBody body = new FormBody.Builder()
                    .add("acctid", "5faa4907e6a75e")
                    .add("username", createUserName==null?"ts_AUDIT":createUserName)
//                    .add("username", "ts_demo")  //金蝶登录验证用户指定为ts_demo
                    .add("appid", "227281_Xf7D7zhpykB9R9VHx61oU6zr6rw7wKmK")
                    .add("signeddata", "694c16895c9ec62985af219b89ae846e39bac28b1bd80f0b4bf1e00854017c3d")
                    .add("appSecret", "bf1f5946e06745f7a3f1f229d8108290")
                    .add("timestamp", "1721261356")
                    .add("origintype", "SimPas")
                    .add("lcid", "2052")
                    .build();

            Request request = new Request.Builder()
                    .url(LOGIN_URL)
                    .post(body)
                    .build();

            try {
                Response response = client.newCall(request).execute();
                if (response.isSuccessful()) {
                    String result = response.body().string();
                    JSONObject jsonResult = new JSONObject(result);
                    int loginResultType = jsonResult.getInt("LoginResultType");
                    if (loginResultType == 1) {
                        JSONObject Context = jsonResult.getJSONObject("Context");
                        String sessionId = Context.getString("SessionId");
                        String kdsvcSessionId = jsonResult.getString("KDSVCSessionId");

                        writeToCookie(sessionId, kdsvcSessionId);
                        callback.onSuccess( );
                    } else {
                        callback.onFailure("ERP账号校验登录失败");
                    }
                } else {
                    callback.onFailure("ERP账号校验请求失败: " + response.code());
                }
            } catch (IOException | JSONException e) {
                callback.onFailure("ERP服务器连接失败，请检查网络是否正确" );
            }
        }).start();
    }


    private void writeToCookie(String sessionId, String kdsvcSessionId) {

        SharedPreferences sharedPreferences = context.getSharedPreferences(PREFS_NAME, MODE_PRIVATE);


        SharedPreferences.Editor editor = sharedPreferences.edit();


        editor.putString("sessionId", sessionId);
        editor.putString("kdsvcSessionId", kdsvcSessionId);


        editor.apply();
    }

    public interface LoginCallback {
        void onSuccess( );
        void onFailure(String errorMessage);
    }

    public void saveCredentials(String username, String password) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("username", username);
        editor.putString("password", password);
        editor.apply();
    }

    public String getUsername() {
        SharedPreferences sharedPreferences = context.getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        return sharedPreferences.getString("username", "");
    }

    public String getPassword() {
        SharedPreferences sharedPreferences = context.getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        return sharedPreferences.getString("password", "");
    }
}
